package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sengMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            System.out.println("code = " + code);

            // SMSUtils.sendMessage();

            // session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success(code);
        }

        return R.error("手机号码为空！验证码发送失败!");
    }


    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {
        //获取map中的phone and code
        String phone = (String)map.get("phone");
        String code = (String) map.get("code");
        //获取在session中的phone 验证码值
        // String variableCode = (String) session.getAttribute(phone);
        String variableCode = (String) redisTemplate.opsForValue().get(phone);

        //判断session中phone value is not null  != null && equals
        if (StringUtils.isNotEmpty(variableCode) && variableCode.equals(code)) {

            //进入判断体创建一个选择器对象
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            //通过唯一的电话号码 查询 唯一的用户数据
            qw.eq(!"".equals(phone),User::getPhone,phone );
            User user = userService.getOne(qw);
            //如果用户数据为空
            if (user == null) {
                //new user() 对象 封装 phone 电话 status 状态为 1 name 为 u_+电话号码
                user = new User();
                user.setName("u_"+phone);
                user.setStatus(1);
                user.setPhone(phone);
                //调用service服务层对user对象 进行持久化保存
                userService.save(user);

            }
            session.setAttribute("user",user.getId());
            //删除存储在redis库中的验证码data
            redisTemplate.delete(phone);
            return R.success(user);    //返回登录成功!
        }

        //返回登录失败!
        return R.error("登录失败!"); //user "登录失败!"
    }

    /**
     * 退出登录
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        // request.getSession().invalidate();               //方式一:消除整个会话对象
        request.getSession().removeAttribute("user");   //方式二:销毁移动端会话元素
        BaseContext.setCurrentId(null);                     //重置线程数据
        return R.success("登出成功!");
    }
}
